<?php

namespace app\api\logic;
use app\admin\logic\BasicLogic;
use app\order\logic\OrderListLogic;
use think\facade\Db;
use app\checkbill\model\Qqwyskuweight;
use app\data\util\HttpUtil;

class TrackLogic extends BasicLogic
{

    /**
     * @desc 无忧对账对账
     * @date 2024-03-22
     */
    public function reconciliation_qqwy($id = null){
        if (empty($id)) {
            // $checkbill_qqwy = array();
            // $checkbill = Db::name('checkbill')
            //     ->where('type',2)
            //     ->where('status',"working")
            //     ->order('createtime asc')
            //     ->find();
            // if(!empty($checkbill)){
                $checkbill_qqwy = Db::name('checkbill_qqwy')
                    ->where('reconciliation_status',0)
                    ->where('reference_no',">",0)
                    ->limit(50)
                    ->select()
                    ->toarray();
                // if(empty($checkbill_qqwy)){
                //     //任务完成
                //     $this->qqwy_success($checkbill['id']);
                //     return false;
                // }
            // }
        } else {
            $checkbill_qqwy = Db::name('checkbill_qqwy')
                ->where('id',$id)
                ->find();
        }
        if (!empty($checkbill_qqwy)) {
            foreach ($checkbill_qqwy as $k=>$v) {
                // $checkbill_qqwy = $this->reconciliationinfo_qqwy_self($v);
                $checkbill_qqwy = $this->reconciliationinfo_qqwy($v);
            }
            return $checkbill_qqwy;
        } else {
            return false;
        }
    }
    /**
    * 方法详情
    * @param array params
    */
    public function reconciliationinfo_qqwy($checkbill_qqwy)
    {
        $checkbill_qqwy['reference_no'] = trim($checkbill_qqwy['reference_no']);
        $checkbill_qqwy['postal'] = trim($checkbill_qqwy['postal']);
        $checkbill_qqwy['total_weight'] = trim($checkbill_qqwy['total_weight']);
        //分区
        $postal = (int)substr($checkbill_qqwy['postal'],0,3);
        $recon_qqwy_zone = Db::name('checkbill_qqwyzone')
            ->where('postal_code_start',"<=",$postal)
            ->where('postal_code_end',">=",$postal)
            ->find();
        if(!empty($recon_qqwy_zone)){
            $zone_id_new = $recon_qqwy_zone['zone_id'];
        }else{
            $zone_id_new = trim($checkbill_qqwy['zone_id']);
        }
        //总重量
        $total_weight_new = 0;
        //件数
        $pieces_new = 0;
        if(!empty($checkbill_qqwy['reference_no'])){
            $info = Db::name('gettrackskuinfo')
                ->alias('f')
                ->leftJoin('ba_gettrackorderinfo o', 'f.sku_id = o.sku_id')
                ->where('o.order_id', $checkbill_qqwy['reference_no'])
                ->field('f.sku_id, f.new_sku,f.count as qtyOrdered')
                ->select()->toArray();
            $outputArray = [];
            foreach ($info as $item) {
                $sku = $item['new_sku'];
                if (isset($outputArray[$sku])) {
                    $outputArray[$sku]['qtyOrdered'] += $item['qtyOrdered'];
                } else {
                    $outputArray[$sku] = $item;
                }
            }
            $OrderDetail3 = array_values($outputArray);
            if(!empty($OrderDetail3)){
                $skus = array_column($OrderDetail3,'new_sku');
                $weightInfo =  (new Qqwyskuweight())->where([
                    'new_sku' => $skus
                ])->field('new_sku,weight')->select()->toArray();
                $weightInfoMap = array_column($weightInfo,null,'new_sku');
                $info          = array_column($OrderDetail3,null,'new_sku');
                foreach($info as $v){
                    $weightValues       = $weightInfoMap[$v['new_sku']]??[];
                    $weight             = isset($weightValues['weight'])&&$weightValues['weight'] ? intval($weightValues['weight']*$v['qtyOrdered']) : 0;
                    $total_weight_new        +=$weight;
                    $pieces_new           +=$v['qtyOrdered'];
                }
            }
        }
        //运费
        $operating_fee_news = 0;
        $operating_fee_news2 = 0;
            if(!empty($total_weight_new)){
                //运费-程序计算
                $total_weight_new = (float)number_format($total_weight_new/1000, 2, '.', '');
                $recon_qqwy_zoneweight = Db::name('checkbill_qqwyzoneweight')
                    ->where('weight_range_star',"<=",$total_weight_new)
                    ->where('weight_range_end',">=",$total_weight_new)
                    ->where('zone_id',"=",$zone_id_new)
                    ->find();
                if(!empty($recon_qqwy_zoneweight)){
                    $operating_fee_news = $recon_qqwy_zoneweight['freight_cost'];
                }
            }
            //运费-程序计算(使用账单的重量来计算)
            if(!empty($checkbill_qqwy['total_weight'])){
                $recon_qqwy_zoneweight2 = Db::name('checkbill_qqwyzoneweight')
                ->where('weight_range_star',"<=",$checkbill_qqwy['total_weight'])
                ->where('weight_range_end',">=",$checkbill_qqwy['total_weight'])
                ->where('zone_id',"=",$zone_id_new)
                ->find();
                if(!empty($recon_qqwy_zoneweight2)){
                    $operating_fee_news2 = $recon_qqwy_zoneweight2['freight_cost'];
                }
            }
            $update = array();
            $update['zone_id_new'] = $zone_id_new;
            $update['total_weight_new'] = $total_weight_new;
            $update['pieces_new'] = $pieces_new;
            $update['operating_fee_news'] = $operating_fee_news;
            $update['operating_fee_news2'] = $operating_fee_news2;
            $update['reconciliation_status'] = 1;
            Db::name('checkbill_qqwy')
                ->where('id',$checkbill_qqwy['id'])
                ->update($update); 
            return $update;
    }

    /**
    * 任务完成
    * @param array params
    */
    public function qqwy_success($checkbill_id)
    {
        $update['status'] = 'success';
        $checkbill = Db::name('checkbill')
            ->where('id',$checkbill_id)
            ->where('status',"working")
            ->update($update);
        if(!empty($checkbill)){
            //成功则导出成表格
            $this->export($checkbill_id);
        }
    }

    /**
    * 导出
    * @param array params
    */
    public function export($checkbill_id)
    {
        return true;
    }
    

    /**
     * @desc SKU数量以及订单运费对账
     * @date 2024-03-22
     */
    public function reconciliation_order($id = null){
        if (empty($id)) {
            $checkbill_order = array();
            $checkbill = Db::name('checkbill')
                ->where('type',4)
                ->where('status',"working")
                ->order('createtime asc')
                ->find();
            if(!empty($checkbill)){
                $checkbill_order = Db::name('checkbill_order')
                    ->where('reconciliation_status',0)
                    ->where('checkbill_id',$checkbill['id'])
                    ->where('reference_no',">",0)
                    ->limit(50)
                    ->select()
                    ->toarray();
                if(empty($checkbill_order)){
                    //任务完成
                    $this->qqwy_success($checkbill['id']);
                    return false;
                }
            }
        } else {
            $checkbill_order = Db::name('checkbill_order')
                ->where('id',$id)
                ->select();
        }
        if (!empty($checkbill_order)) {
            foreach ($checkbill_order as $k=>$v) {
                $checkbill_order = $this->reconciliationinfo_order($v);
            }
            return $checkbill_order;
        } else {
            return false;
        }
    }
    /**
    * 方法详情
    * @param array params
    */
    public function reconciliationinfo_order($checkbill_order)
    {
        $checkbill_order['reference_no'] = trim($checkbill_order['reference_no']);
        $checkbill_order['seller_sku'] = trim($checkbill_order['seller_sku']);
        $checkbill_order['quantity'] = trim($checkbill_order['quantity']);
        //运费
        $checkbill_ordercost = Db::name('checkbill_ordercost')->where('reference_no',$checkbill_order['reference_no'])->find();
        $update = array();
        //运单号
        if(isset($checkbill_ordercost['waybill_no']) && !empty($checkbill_ordercost['waybill_no'])){
            $update['logistics_costs'] = $checkbill_ordercost['cost'];
            $update['waybill_no_new'] = $checkbill_ordercost['waybill_no'];
        }else{
            $waybill_no_new = Db::name('gettrackorder')->where('order_id',$checkbill_order['reference_no'])->find();
            $update['waybill_no_new'] = $waybill_no_new['tracking_number'];
            $checkbill_ordercost = Db::name('checkbill_ordercost')->where('waybill_no',$waybill_no_new['tracking_number'])->find();
            if(isset($checkbill_ordercost['cost']) && !empty($checkbill_ordercost['cost'])){
                $update['logistics_costs'] = $checkbill_ordercost['cost'];
            }
        }
        //SKU
        $productsku = $this->productsku($checkbill_order);
        $update['brand'] = $productsku['brand'];
        $update['pieces_new'] = $productsku['pieces_new'];

        $update['reconciliation_status'] = 1;
        Db::name('checkbill_order')
            ->where('id',$checkbill_order['id'])
            ->update($update); 
        return $update;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function productsku($v)
    {
        $productsku['brand'] = "";
        $productsku['pieces_new'] = 0;
        $count = 0;
        if (!empty($v['seller_sku']) && !empty($v['quantity'])) {
            //拆分规则
            $pos1 = strpos($v['seller_sku'], '+');
            if ($pos1 !== false) {
                $pos = strpos($v['seller_sku'], '-');
                if ($pos !== false) {
                    $sku = explode('-', $v['seller_sku']);
                    $productsku['brand'] = $sku[0];
                    $combination_sku = explode('+', $sku[1]);
                    $count = count($combination_sku);
                    if(isset($sku[3]) && !empty($sku[3])){
                        $count = (int)number_format((int)$sku[3] * (int)$count, 0, '.', '');
                    }
                }else{
                    $count = 2;
                }
            } else {
                $pos = strpos($v['seller_sku'], '-');
                if ($pos !== false) {
                    $sku = explode('-', $v['seller_sku']);
                    $productsku['brand'] = $sku[0];
                    if (isset($sku[3])) {
                        if (is_numeric($sku[3])) {
                            $count = $sku[3];
                        }
                    } else {
                        $count = 1;
                    }
                }else{
                    $count = 2;
                }
            }
            $count = (int)number_format((int)$v['quantity'] * (int)$count, 0, '.', '');
        }
        $productsku['pieces_new'] = $count;
        return $productsku; 
    }
    
    /**
     * @desc 顺丰对账
     * @date 2024-03-22
     */
    public function reconciliation_sf($id = null){
        if (empty($id)) {
            $checkbill_sf = Db::name('checkbill_sf')->where('reconciliation_status',0)->find();
        } else {
            $checkbill_sf = Db::name('checkbill_sf')
                ->where('id',$id)
                ->find();
        }
        if (!empty($checkbill_sf)) {
            //如果是SELF_PICKUP_EXPRESS
            if($checkbill_sf['code'] == "SELF_PICKUP_EXPRESS"){
                $checkbill_sf = $this->reconciliationinfo_sf_self($checkbill_sf);
            }else{
                $checkbill_sf = $this->reconciliationinfo_sf($checkbill_sf);
            }
            return $checkbill_sf;
        } else {
            return false;
        }
    }
    /**
     * @desc 提前算sku
     */
    public function CalculateSKUInAdvance($id = null){
        $checkbill_sf = Db::name('test_order')->where('type',0)->limit(50)->select();
        if (!empty($checkbill_sf)) {
            foreach ($checkbill_sf as $k=>$v) {
                $test_order_quantity = [];
                if(!empty($v['id'])){
                    $test_order_quantity = Db::name('test_order_quantity')->where('order_id',$v['id'])->select();
                }
                $skuinfo = "";
                $skuinfo2 = "";
                if(!empty($test_order_quantity)){
                    //添加
                    if(!empty($v['id'])){
                        Db::name('test_orderskuinfo')->where('order_id',$v['id'])->delete();
                    }
                    $inserts = [];
                    foreach ($test_order_quantity as $kq=>$vq) {
                        $insert = [];
                        $insert['order_id'] = $vq['order_id'];
                        $insert['sku'] = $vq['seller_sku'];
                        $productsku = $this->productsku($vq);
                        $insert['num'] = $productsku['pieces_new'];;
                        $insert['spu'] = $productsku['brand'];
                        $inserts[] = $insert;

                        if(!empty($skuinfo)){
                            $skuinfo = $skuinfo.",".$vq['seller_sku']. "*" .$vq['quantity'];
                        }else{
                            $skuinfo = $vq['seller_sku']. "*" .$vq['quantity'];
                        }

                        if(!empty($skuinfo2)){
                            $skuinfo2 = $skuinfo2.",".$insert['spu']. "*" .$insert['num'];
                        }else{
                            $skuinfo2 = $insert['spu']. "*" .$insert['num'];
                        }

                    }
                    Db::name('test_orderskuinfo')->insertAll($inserts);
                }
                $update = [];
                $update['skuinfo'] = $skuinfo;
                $update['skuinfo2'] = $skuinfo2;
                $update['type'] = 2;
                Db::name('test_order')->where('id',$v['id'])->update($update);
                
                
            }
            return true;
        } else {
            return false;
        }
    }
    
    /**
    * 顺丰
    * @param array params
    */
    public function reconciliationinfo_sf($checkbill_sf)
    {
        $checkbill_sf['reference_no'] = trim($checkbill_sf['reference_no']);
        $checkbill_sf['postal'] = trim($checkbill_sf['postal']);
        $checkbill_sf['total_weight'] = trim($checkbill_sf['total_weight']);

        $return = $this->get_order_check($checkbill_sf['reference_no']);
        // dump($return);die;
        //折后运费
        if(isset($return['total_weight']) && !empty($return['total_weight'])){
            //总重量修改成长*宽*高/6000 换算成g 
            $return['total_weight'] = (float)number_format($checkbill_sf['total_weight']*1000, 2, '.', '');
            //分区
            $postal = (int)substr($checkbill_sf['postal'],0,3);
            $recon_sf_zone = Db::name('checkbill_sfzone')
                ->where('postal_code_start',"<=",$postal)
                ->where('postal_code_end',">=",$postal)
                ->find();
            if(!empty($recon_sf_zone)){
                $checkbill_sf['zone_id'] = $recon_sf_zone['zone_id'];
            }else{
                $checkbill_sf['zone_id'] = $checkbill_sf['zone_id'];
            }
            //运费-程序计算
            $checkbill_sfzoneweight = Db::name('checkbill_sfzoneweight')
                ->where('weight_range_star',"<=",$checkbill_sf['total_weight'])
                ->where('weight_range_end',">=",$checkbill_sf['total_weight'])
                ->where('zone_id',"=",$checkbill_sf['zone_id'])
                ->find();
            if(!empty($checkbill_sfzoneweight)){
                $discounted_shipping_new = $checkbill_sfzoneweight['freight_cost'];
            }else{
                $discounted_shipping_new = 0;
            }
            //操作费
            $operating_fee_news = 0;
            $multiple_pieces = $return['total_num'] - 1;//多件
            if($return['type_menue'] == 0){//一品
                if($multiple_pieces >=1){
                    $operating_fee_news = (float)number_format($multiple_pieces*2.38+3.24, 2, '.', '');
                }else{
                    $operating_fee_news = 3.24;
                }
            }
            if($return['type_menue'] == 1){//多品
                if($multiple_pieces >=1){
                    $operating_fee_news = (float)number_format($multiple_pieces*2.57+3.24, 2, '.', '');
                }else{
                    $operating_fee_news = 3.24;
                }
            }
            //最终数据
            // $update['total_weight_new'] = $return['total_weight'];
            // $update['height_new'] = $checkbill_sf['total_height'];
            $update['total_weight_new'] = (float)number_format($return['total_weight']/1000, 2, '.', '');
            $update['pieces_new'] = $return['total_num'];
            // $update['discounted_shipping_new'] = $discounted_shipping_new;
            $update['operating_fee_news'] = $operating_fee_news;
            $update['reconciliation_status'] = 1;
            $update['zone_id_new'] = $checkbill_sf['zone_id'];
            $update['discounted_shipping_new'] = $discounted_shipping_new;
            Db::name('checkbill_sf')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
            return true;
        }else{
            $update = array();
            $update['reconciliation_status'] = 2;
            Db::name('checkbill_sf')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
        }
        return true;
    }

    /**
    * 顺丰
    * @param array params
    */
    public function reconciliationinfo_sf_self($checkbill_sf)
    {
        $update = array();
        $return = Db::name('order')->where('order_id',$checkbill_sf['reference_no'])->find();
        if(isset($return) && !empty($return)){
            $update['reconciliation_status'] = 1;
            Db::name('checkbill_sf')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
        }else{
            $update['reconciliation_status'] = 2;
            Db::name('checkbill_sf')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
        }
        return true;
    }

    //顺丰处理数据
    public function get_order_check($order_id=''){
        if(!$order_id)   return "order_id不能为空!";
        $result = Db::name('gettrackskuinfo')
            ->alias('f')
            ->leftJoin('ba_gettrackorderinfo o', 'f.sku_id = o.sku_id')
            ->where('o.order_id', $order_id)
            ->field('f.sku_id, f.new_sku,f.count as qtyOrdered')
            ->select()->toArray();
        if(!$result)   return "暂无数据!";
        
        $list = self::getQtyOrdered($result);
        $total_info   = self::getTotalWeight($list);
        $total_weight = $total_info['totalWeight']??0;
        $total_num    = $total_info['totalNum']??0;
        $type_menue   = count($list) == 1 ? 0 : 1; //单品还是多品,0:单品  1:多品
        $total_height = self::getTotalHeight($list);
        return [
            'total_weight'=>$total_weight,
            'total_num'  =>$total_num,
            'total_height'=>$total_height,
            'type_menue'  =>$type_menue,
        ];
    }

    /**
     * @desc 数据统计
     * @date 2024-02-22
     */
    public function getQtyOrdered($info){
        $outputArray = [];
        foreach ($info as $item) {
            $sku = $item['new_sku'];
            if (isset($outputArray[$sku])) {
                $outputArray[$sku]['qtyOrdered'] += $item['qtyOrdered'];
            } else {
                $outputArray[$sku] = $item;
            }
        }
        return array_values($outputArray);
    }


    /**
     * @desc 获取发货总重量;
     * @author xx
     * @date 2024-02-22
     */
    public function getTotalWeight($OrderDetail3){
        if(!$OrderDetail3) return  0;
        $skus = array_column($OrderDetail3,'new_sku');
        //品牌不同的情况
        $skus = $skus[0];
        if(!empty($skus)){
            $pos = strpos($skus, '-');
            if ($pos !== false) {
                $skusArray = explode('-', $skus);
                // 获取黑色和尺码部分
                $skus = $skusArray[1] . '-' . $skusArray[2];
            }
        }

        if ($skus) {
            $where[] = ['new_sku', 'like', '%' . $skus . '%'];
        }
        
        $weightInfo = Db::name('checkbill_sfskuweight')->where($where)->field('new_sku,weight')->select()->toArray();
        // dump($skus);die;
        $weightInfoMap = array_column($weightInfo,null,'new_sku');
        $info          = array_column($OrderDetail3,null,'new_sku');
        $totalWeight   = 0;
        $totalNum      = 0;
        foreach($info as $v){
            $weightValues       = $weightInfoMap[$v['new_sku']]??[];
            $weight             = isset($weightValues['weight'])&&$weightValues['weight'] ? intval($weightValues['weight']*$v['qtyOrdered']) : 0;
            $totalWeight        +=$weight;
            $totalNum           +=$v['qtyOrdered'];
        }
        return ['totalWeight'=>$totalWeight,'totalNum'=>$totalNum];
    }


    /**
     * @desc 获取总高度
     */
    public function getTotalHeight($list){
        if(!$list) return  0;
        $skus = array_column($list,'new_sku');
        //品牌不同的情况
        $skus = $skus[0];
        if(!empty($skus)){
            $pos = strpos($skus, '-');
            if ($pos !== false) {
                $skusArray = explode('-', $skus);
                // 获取黑色和尺码部分
                $skus = $skusArray[1] . '-' . $skusArray[2];
            }
        }


        if ($skus) {
            $where[] = ['new_sku', 'like', '%' . $skus . '%'];
        }

        $info =Db::name('checkbill_sfskuweight')
            ->where($where)
            ->field('new_sku,heigth')
            ->select()
            ->toArray();
        if(!$info)  return 0;
        $totalHeight = 0;
        $info_map = array_column($info,null,'new_sku');
        foreach($list as $v){
            $heightValues       = $info_map[$v['new_sku']]??[];
            $height             = isset($heightValues['heigth'])&&$heightValues['heigth'] ? intval($heightValues['heigth']*$v['qtyOrdered']) : 0;
            $totalHeight        +=$height;
        }
        return  $totalHeight;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function weight_range_v2($weight){
        $weight_range_id = 0;
        if ($weight >= 1 && $weight <= 28) {
            $weight_range_id = 1;
        } elseif ($weight >= 29 && $weight <= 56) {
            $weight_range_id = 2;
        } elseif ($weight >= 57 && $weight <= 84) {
            $weight_range_id = 3;
        } elseif ($weight >= 85 && $weight <= 112) {
            $weight_range_id = 4;
        } elseif ($weight >= 113 && $weight <= 140) {
            $weight_range_id = 5;
        } elseif ($weight >= 141 && $weight <= 168) {
            $weight_range_id = 6;
        } elseif ($weight >= 169 && $weight <= 196) {
            $weight_range_id = 7;
        } elseif ($weight >= 197 && $weight <= 224) {
            $weight_range_id = 8;
        } elseif ($weight >= 225 && $weight <= 252) {
            $weight_range_id = 9;
        } elseif ($weight >= 253 && $weight <= 280) {
            $weight_range_id = 10;
        } elseif ($weight >= 281 && $weight <= 308) {
            $weight_range_id = 11;
        } elseif ($weight >= 309 && $weight <= 336) {
            $weight_range_id = 12;
        } elseif ($weight >= 337 && $weight <= 364) {
            $weight_range_id = 13;
        } elseif ($weight >= 365 && $weight <= 392) {
            $weight_range_id = 14;
        } elseif ($weight >= 393 && $weight <= 420) {
            $weight_range_id = 15;
        } elseif ($weight >= 421 && $weight <= 448) {
            $weight_range_id = 16;
        }elseif ($weight >= 449 && $weight <= 450) {
            $weight_range_id = 17;
        }elseif ($weight >= 451 && $weight <= 900) {
            $weight_range_id = 18;
        }elseif ($weight >= 901 && $weight <= 1350) {
            $weight_range_id = 19;
        }elseif ($weight >= 1351 && $weight <= 1800) {
            $weight_range_id = 20;
        }elseif ($weight >= 1801 && $weight <= 2250) {
            $weight_range_id = 21;
        }elseif ($weight >= 2251 && $weight <= 2700) {
            $weight_range_id = 22;
        }elseif ($weight >= 2701 && $weight <= 3150) {
            $weight_range_id = 23;
        }elseif ($weight >= 3151 && $weight <= 3600) {
            $weight_range_id = 24;
        }elseif ($weight >= 3601 && $weight <= 4050) {
            $weight_range_id = 25;
        }elseif ($weight >= 4051) {
            $weight_range_id = 26;
        }
        return $weight_range_id;
    }
    
    /**
    * 顺丰
    * @param array params
    */
    public function reconciliationinfo_qqwy_self($checkbill_sf)
    {
        $update = array();
        $return = Db::name('order')->where('order_id',$checkbill_sf['reference_no'])->find();
        if(isset($return) && !empty($return)){
            $update['reconciliation_status'] = 1;
            Db::name('checkbill_qqwy')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
        }else{
            $update['reconciliation_status'] = 2;
            Db::name('checkbill_qqwy')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
        }
        return true;
    }
    
    /**
     * @desc 旧金山对账对账
     * @date 2024-03-22
     */
    public function reconciliation_jjs($id = null){
        if (empty($id)) {
                $checkbill_qqwy = Db::name('checkbill_jjs')
                    ->where('reconciliation_status',0)
                    ->where('reference_no',">",0)
                    ->limit(50)
                    ->select()
                    ->toarray();
        } else {
            $checkbill_qqwy = Db::name('checkbill_jjs')
                ->where('id',$id)
                ->find();
        }
        if (!empty($checkbill_qqwy)) {
            foreach ($checkbill_qqwy as $k=>$v) {
                $checkbill_qqwy = $this->reconciliationinfo_jjs($v);
            }
            return $checkbill_qqwy;
        } else {
            return false;
        }
    }

    /**
    * 方法详情
    * @param array params
    */
    public function reconciliationinfo_jjs($checkbill_qqwy)
    {
        $checkbill_qqwy['reference_no'] = trim($checkbill_qqwy['reference_no']);
        $checkbill_qqwy['postal'] = trim($checkbill_qqwy['postal']);
        $checkbill_qqwy['total_weight'] = trim($checkbill_qqwy['total_weight']);
        //分区
        $zone_id_new = trim($checkbill_qqwy['zone_id']);
        //总重量
        $total_weight_new = 0;
        //件数
        $pieces_new = 0;
        if(!empty($checkbill_qqwy['reference_no'])){
            $info = Db::name('gettrackskuinfo')
                ->alias('f')
                ->leftJoin('ba_gettrackorderinfo o', 'f.sku_id = o.sku_id')
                ->where('o.order_id', $checkbill_qqwy['reference_no'])
                ->field('f.sku_id, f.new_sku,f.count as qtyOrdered')
                ->select()->toArray();
            $outputArray = [];
            foreach ($info as $item) {
                $sku = $item['new_sku'];
                if (isset($outputArray[$sku])) {
                    $outputArray[$sku]['qtyOrdered'] += $item['qtyOrdered'];
                } else {
                    $outputArray[$sku] = $item;
                }
            }
            $OrderDetail3 = array_values($outputArray);
            if(!empty($OrderDetail3)){
                $skus = array_column($OrderDetail3,'new_sku');
                $weightInfo =  (new Qqwyskuweight())->where([
                    'new_sku' => $skus
                ])->field('new_sku,weight')->select()->toArray();
                $weightInfoMap = array_column($weightInfo,null,'new_sku');
                $info          = array_column($OrderDetail3,null,'new_sku');
                foreach($info as $v){
                    $weightValues       = $weightInfoMap[$v['new_sku']]??[];
                    $weight             = isset($weightValues['weight'])&&$weightValues['weight'] ? intval($weightValues['weight']*$v['qtyOrdered']) : 0;
                    $total_weight_new        +=$weight;
                    $pieces_new           +=$v['qtyOrdered'];
                }
            }
        }
        //运费
        $operating_fee_news = 0;
        $operating_fee_news2 = 0;
            if(!empty($total_weight_new)){
                //运费-程序计算
                $total_weight_new = (float)number_format($total_weight_new/1000, 2, '.', '');
                $recon_qqwy_zoneweight = Db::name('checkbill_jjszoneweight')
                    ->where('weight_range_star',"<=",$total_weight_new)
                    ->where('weight_range_end',">=",$total_weight_new)
                    ->where('zone_id',"=",$zone_id_new)
                    ->find();
                if(!empty($recon_qqwy_zoneweight)){
                    $operating_fee_news = $recon_qqwy_zoneweight['freight_cost'];
                }
            }
            //运费-程序计算(使用账单的重量来计算)
            if(!empty($checkbill_qqwy['total_weight'])){
                $recon_qqwy_zoneweight2 = Db::name('checkbill_jjszoneweight')
                ->where('weight_range_star',"<=",$checkbill_qqwy['total_weight'])
                ->where('weight_range_end',">=",$checkbill_qqwy['total_weight'])
                ->where('zone_id',"=",$zone_id_new)
                ->find();
                if(!empty($recon_qqwy_zoneweight2)){
                    $operating_fee_news2 = $recon_qqwy_zoneweight2['freight_cost'];
                }
            }
            $update = array();
            $update['zone_id_new'] = $zone_id_new;
            $update['total_weight_new'] = $total_weight_new;
            $update['pieces_new'] = $pieces_new;
            $update['operating_fee_news'] = $operating_fee_news;
            $update['operating_fee_news2'] = $operating_fee_news2;
            $update['reconciliation_status'] = 1;
            Db::name('checkbill_jjs')
                ->where('id',$checkbill_qqwy['id'])
                ->update($update); 
            return $update;
    }

    



    /**
     * @desc    register注册订单
     * @author  zhangheng
     * @date    2024-05-29
     */
    public function track_register($params=[])
    {

        // $track_number = $params['tracking_number']??'';
        // if(!$track_number)  return ['msg'=>'物流单号为空'];
        // htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/track_register/' . date('Ymd') . '.txt');
        // $url     = Config('Logisticskey.17_track.base_url');
        // $arr     = [];
        // $arr[]   = ['number'=>$track_number];
        // $res     = HttpUtil::trackPostUrl($url, $arr);
        // htmlLog(['response'=>$res,'tracking_number'=>$track_number],OPERATE_LOG . date('Ym') . '/track_register/' . date('Ymd') . '.txt');
        return true;
    }


    /**
     * @desc    消息已读变更
     * @author  luckyXiong
     * @date    2024-05-31
     */
    public function conversations_read_queue($params=[]){
        htmlLog(['param'=>$params],OPERATE_LOG . date('Ym') . '/conversations_read_queue/' . date('Ymd') . '.txt');
        $conversation_id  = $params['conversation_id']??'';
        $order_id         = $params['order_id']??'';
        $shop_id          = $params['shop_id']??'';
        $where            = [];
        $where[]          = ['conversation_id','=',$conversation_id];
        $where[]          = ['order_id','=',$order_id];
        $where[]          = ['message_role','<>','BUYER'];
        $list             = Db::name('im_conversations_message')
                           ->where($where)
                           ->select();
        $list            = objectToArray($list);
        $num             = count($list);
        if($num>1){
            htmlLog(['conversation_id'=>$conversation_id],OPERATE_LOG . date('Ym') . '/conversations_read_queue/' . date('Ymd') . '.txt');
            //更新主表数据;
            Db::name('im_conversations')->where(['shop_id'=>$shop_id,'conversation_id'=>$conversation_id])->update(['conversations_unread_count'=>0]);
        }
    }


    /**
     * @desc    获取海鱼订单数据
     * @author  luckyXiong
     * @date    2024-06-13
     */
    public function get_haiyu_order($params=[]){
             $data = $params['data']['orders']??[];
             foreach($data as $v){
                 self::get_order_info($v);
             }
    }




    /**
     * @desc    获取海鱼订单数据
     * @author  luckyXiong
     * @date    2024-06-13
     */
    public function get_order_info($orderinfo){
        $orderinfo['shop_id']    = 16;
        $shop['time_zone']       = 15;
        if($shop['time_zone']){
            $orderinfo['createtime'] = $orderinfo['create_time'] - $shop['time_zone'] * 3600;
        }else{
            $orderinfo['createtime'] = $orderinfo['create_time'];
        }

        $exist_info = Db::name('order')->where('order_id',$orderinfo['id'])->find();
        if($exist_info){
            return  '数据已经存在!';
        }

        //获取写入数据组装;
        $arr_info = (new OrderListLogic())->get_arr_info($orderinfo);
        //批量写入数据;
        Db::name('order')->insert($arr_info['order_arr']);
        Db::name('order_info')->insertAll($arr_info['order_info_arr']);
        Db::name('order_append')->insert($arr_info['order_append_arr']);
    }









}